import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import CircularProgress from '@mui/material/CircularProgress';
import { useState, useEffect } from 'react';
import {
  Stack,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Button,
  Tooltip,
  Pagination,
  Typography,
  Box,
  Fab,
  Tabs,
  Tab,
  Chip,
  Alert,
} from '@mui/material';
import { Add, TrendingUp, TrendingDown } from '@mui/icons-material';
import { formatDate } from '../../utils/format-time';
import { BillForm } from './bill-form';
import { BillStatistics } from './bill-statistics';

export function CashBookTable() {
  // 表格数据的状态
  const [rows, setRows] = useState([]);
  const [details, setDetails] = useState([]);
  const [pageNumber, setPageNumber] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(8); // 每页条目数量
  const [pages, setPages] = useState(0); // 总页数
  const [openDialog, setOpenDialog] = useState(false); // 控制模态框显示与否
  const [dialogTitle, setDialogTitle] = useState(''); // 模态框标题
  const [loadingDetails, setLoadingDetails] = useState(false); // 控制数据加载状态
  const [detailsRows, setDetailsRows] = useState(false); // 控制数据加载状态
  const [loading, setLoading] = useState(false); // 控制数据加载状态
  
  // 新增状态
  const [showBillForm, setShowBillForm] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const [currentTab, setCurrentTab] = useState(0);
  const [showStatistics, setShowStatistics] = useState(true);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  const formatNumber = (number) => {
    if (number === null || number === undefined || isNaN(number)) {
      return '0.00';
    }
    return Number(number).toFixed(2);
  }; // Round the number to 2 decimal places

  const fetchData = () => {
    setLoading(true);
    const params = {
      pageNumber,
      pageSize,
    };

    // 根据当前标签页选择不同的API
    let apiUrl = '/api/cash/book/query';
    if (currentTab === 1) {
      apiUrl = '/api/cash/book/income';
    } else if (currentTab === 2) {
      apiUrl = '/api/cash/book/expense';
    }

    fetch(apiUrl, {
      method: currentTab === 0 ? 'POST' : 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `${localStorage.getItem('token') !== null ? `Bearer ${localStorage.getItem('token')}` : null}`,
      },
      body: currentTab === 0 ? JSON.stringify(params) : undefined,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`API请求失败: ${response.status}`);
        }
        return response.json();
      })
      .then((result) => {
        // 处理不同的响应结构
        let data;
        if (result.success && result.data) {
          data = result.data;
        } else if (result.success && !result.data) {
          data = result;
        } else if (result.code === 200) {
          data = result.data || result;
        } else {
          data = result;
        }

        // 确保数据存在
        if (data && data.list) {
          setRows(data.list);
          setPages(data.pages || 1);
        } else {
          // 如果没有数据，设置空数组
          setRows([]);
          setPages(1);
        }
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
        // 设置默认数据，确保页面能正常渲染
        setRows([]);
        setPages(1);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 使用 useEffect 来执行数据加载
  useEffect(() => {
    fetchData();
  }, [pageNumber, pageSize, currentTab]); // 依赖 selectedDate，pageNumber 和 pageSize

  // onChangePage 处理分页变化
  const onChangePage = (event, newPage) => {
    setPageNumber(newPage);
  };

  // 处理 row.amount 点击事件，打开模态框并显示详细信息
  const showDetail = (row) => {
    setDetails([]);
    setLoadingDetails(true);
    fetch(`/api/cash/book/query/${new Date(row.consumerDate).toLocaleDateString('en-CA')}`, {
      method: 'POST',
      headers: {
        Authorization: `${localStorage.getItem('token') !== null ? `Bearer ${  localStorage.getItem('token')}` : null}`,
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`详情请求失败: ${response.status}`);
        }
        return response.json();
      })
      .then((result) => {
        // 处理不同的响应结构
        let data;
        if (result.success && result.data) {
          data = result.data;
        } else if (result.success && !result.data) {
          data = result;
        } else if (result.code === 200) {
          data = result.data || result;
        } else {
          data = result;
        }

        // 确保数据存在
        if (data && data.list) {
          setDetails(data.list);
          setDetailsRows(data.total || data.list.length);
        } else {
          setDetails([]);
          setDetailsRows(0);
        }
        setLoadingDetails(false);
      })
      .catch((error) => {
        console.error('Error fetching details:', error);
        setDetails([]);
        setDetailsRows(0);
        setLoadingDetails(false);
      });
    setDialogTitle(`${formatDate(row.consumerDate)} 消费详情`);
    setOpenDialog(true);
  };

  // 关闭模态框
  const handleCloseDialog = () => {
    setOpenDialog(false);
  };

  // 处理账单表单提交
  const handleBillSubmit = async (formData) => {
    setFormLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await fetch('/api/cash/book/save', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('保存失败');
      }

      const result = await response.json();
      if (result.success) {
        setShowBillForm(false);
        setRefreshTrigger(prev => prev + 1);
        fetchData(); // 刷新表格数据
      } else {
        throw new Error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存账单失败:', error);
      alert(error.message);
    } finally {
      setFormLoading(false);
    }
  };

  // 处理标签页切换
  const handleTabChange = (event, newValue) => {
    setCurrentTab(newValue);
    setPageNumber(1); // 重置页码
  };

  const getTabLabel = (index) => {
    switch (index) {
      case 0: return '全部账单';
      case 1: return '收入';
      case 2: return '支出';
      default: return '全部账单';
    }
  };

  const getAmountColor = (row) => {
    if (row.isIncome) {
      return 'success.main';
    } else if (row.billType === 'TRANSFER_IN') {
      return 'success.main';
    } else if (row.billType === 'TRANSFER_OUT' || row.billType === 'LEND') {
      return 'error.main';
    } else {
      return 'text.primary';
    }
  };

  return (
    <div>
      {/* 统计信息 */}
      {showStatistics && (
        <Box mb={3}>
          <BillStatistics refreshTrigger={refreshTrigger} />
        </Box>
      )}

      {/* 标签页 */}
      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
        <Tabs value={currentTab} onChange={handleTabChange}>
          <Tab label="全部账单" />
          <Tab label="收入" icon={<TrendingUp />} iconPosition="start" />
          <Tab label="支出" icon={<TrendingDown />} iconPosition="start" />
        </Tabs>
      </Box>

      {/* 表格展示 */}
      <TableContainer
        component={Paper}
        style={{
          height: '450px',
          overflow: 'auto',
          position: 'relative',
        }}
      >
        {loading && (
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              zIndex: 10,
            }}
          >
            <CircularProgress />
          </div>
        )}

        <Table sx={{ minWidth: 650 }} aria-label="caption table">
          <TableHead
            style={{
              position: 'sticky',
              top: 0,
              background: '#fff',
              zIndex: 1,
            }}
          >
            <TableRow>
              <TableCell align="center" sx={{ width: '120px' }}>
                消费日期
              </TableCell>
              <TableCell align="center" sx={{ width: '100px' }}>
                账单类型
              </TableCell>
              <TableCell align="center" sx={{ width: '150px' }}>
                最高消费
              </TableCell>
              <TableCell align="center" sx={{ width: '150px' }}>
                最低消费
              </TableCell>
              <TableCell align="center" sx={{ width: '150px' }}>
                消费金额(元)
              </TableCell>
              <TableCell align="center" sx={{ width: '100px' }}>
                消费笔数
              </TableCell>
              <TableCell align="center" sx={{ width: '200px' }}>
                备注
              </TableCell>
            </TableRow>
          </TableHead>

          {rows.length === 0 ? (
            <TableBody>
              <TableRow>
                <TableCell colSpan={7} align="center">
                  <Typography variant="body1" color="textSecondary">
                    没有数据
                  </Typography>
                </TableCell>
              </TableRow>
            </TableBody>
          ) : (
            <TableBody>
              {rows.map((row, index) => (
                <TableRow key={index}>
                  <TableCell align="center">{formatDate(row.consumerDate)}</TableCell>
                  <TableCell align="center">
                    <Chip 
                      label={row.billTypeName || row.billType || '未知'} 
                      size="small"
                      color={row.isIncome ? 'success' : 'default'}
                      variant="outlined"
                    />
                  </TableCell>
                                     <TableCell align="center">{formatNumber(row.maxPay || row.amount)}</TableCell>
                   <TableCell align="center">{formatNumber(row.minPay || row.amount)}</TableCell>
                  <TableCell
                    align="center"
                    onClick={() => showDetail(row)}
                    sx={{
                      cursor: 'pointer',
                      color: getAmountColor(row),
                      textDecoration: 'none',
                      '&:hover': {
                        textDecoration: 'underline',
                      },
                    }}
                  >
                    <Tooltip title="查看详情" arrow placement="top">
                      <span>{formatNumber(row.amount)}</span>
                    </Tooltip>
                  </TableCell>
                  <TableCell align="center">{row.consumerCount}</TableCell>
                  <TableCell align="center">{row.remark}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          )}
        </Table>
      </TableContainer>

      {/* 分页控制 */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
        <Stack spacing={1}>
          <Pagination
            count={pages}
            color="secondary"
            onChange={onChangePage}
            siblingCount={1}
          />
        </Stack>
      </div>

      {/* 添加账单按钮 */}
      <Fab
        color="primary"
        aria-label="add"
        sx={{ position: 'fixed', bottom: 16, right: 16 }}
        onClick={() => setShowBillForm(true)}
      >
        <Add />
      </Fab>

      {/* 账单表单 */}
      <BillForm
        open={showBillForm}
        onClose={() => setShowBillForm(false)}
        onSubmit={handleBillSubmit}
        loading={formLoading}
      />

      {/* 详情对话框 */}
      <Dialog open={openDialog} onClose={handleCloseDialog} maxWidth={'lg'}>
        <DialogTitle align={'center'}>{dialogTitle}</DialogTitle>
        <DialogContent
          sx={{ height: '400px', overflow: 'auto', minHeight: '400px', width: '800px' }}
        >
          {loadingDetails ? (
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100%',
              }}
            >
              <CircularProgress />
            </div>
          ) : details.length === 0 ? (
            <div style={{ textAlign: 'center', marginTop: '20px' }}>
              <Typography variant="body1" color="textSecondary">
                没有数据
              </Typography>
            </div>
          ) : (
            <TableContainer component={Paper} style={{ height: '100%', overflow: 'auto' }}>
              <Table sx={{ minWidth: 650 }} aria-label="details table">
                <TableHead style={{ position: 'sticky', top: 0, background: '#fff', zIndex: 1 }}>
                  <TableRow>
                    <TableCell align="center">消费日期</TableCell>
                    <TableCell align="center">账单类型</TableCell>
                    <TableCell align="center">消费金额(元)</TableCell>
                    <TableCell align="center">付款人</TableCell>
                    <TableCell align="center">收款人</TableCell>
                    <TableCell align="center">备注</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {details.map((row, index) => (
                    <TableRow key={index}>
                      <TableCell align="center">{formatDate(row.consumerDate)}</TableCell>
                      <TableCell align="center">
                        <Chip 
                          label={row.billTypeName || row.billType || '未知'} 
                          size="small"
                          color={row.isIncome ? 'success' : 'default'}
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell align="center" sx={{ color: getAmountColor(row) }}>
                        {formatNumber(row.amount)}
                      </TableCell>
                      <TableCell align="center">{row.payUserName}</TableCell>
                      <TableCell align="center">{row.forUserName}</TableCell>
                      <TableCell align="center">{row.remark}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog} color="primary">
            关闭
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

// 添加默认导出
export default CashBookTable;
